package com.example.framework509.common.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTypeHandler extends BaseTypeHandler<String> {

    public DateTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i,new Timestamp((new Date()).getTime()));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (sqlTimestamp==null)
            return null;
        Date date = new Date(sqlTimestamp.getTime());
        String time = sdf.format(date);
        return time;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (sqlTimestamp==null)
            return null;
        Date date = new Date(sqlTimestamp.getTime());
        String time = sdf.format(date);
        return time;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (sqlTimestamp==null)
            return null;
        Date date = new Date(sqlTimestamp.getTime());
        String time = sdf.format(date);
        return time;
    }
}
